<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="折扣额度" prop="discountAmount">
        <el-input
          v-model="queryParams.discountAmount"
          placeholder="请输入折扣额度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="减价额度" prop="reductionAmount">
        <el-input
          v-model="queryParams.reductionAmount"
          placeholder="请输入减价额度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券使用条件" prop="couponsCondition" label-width="120px">
        <el-input
          v-model="queryParams.couponsCondition"
          placeholder="请输入优惠券使用条件"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="限制使用日期" prop="couponsLimitdate" label-width="120px">
        <el-date-picker clearable
          v-model="queryParams.couponsLimitdate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择限制使用日期">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="店铺id" prop="shopId">-->
<!--        <el-input-->
<!--          v-model="queryParams.shopId"-->
<!--          placeholder="请输入店铺id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['order:coupons:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:coupons:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:coupons:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['order:coupons:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券编号" align="center" prop="couponsId" />
      <el-table-column label="优惠券名称" align="center" prop="couponsDesc" />
      <el-table-column label="优惠类型" align="center" prop="couponsType">
        <template #default="scope">
          <!-- 使用v-html渲染带样式的内容 -->
          <span v-html="formatCouponType(null, null, scope.row.couponsType)"></span>
        </template>
      </el-table-column>
      <el-table-column label="折扣额度" align="center" prop="discountAmount" />
      <el-table-column label="减价额度" align="center" prop="reductionAmount" />
      <el-table-column label="满足价格" align="center" prop="couponsCondition" />
<!--      <el-table-column label="优惠券状态" align="center">-->
<!--        <template #default="scope">-->
<!--          <span v-html="formatCouponStatus(null, null, scope.row.couponsStatus)"></span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="限制使用日期" align="center" prop="couponsLimitdate" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.couponsLimitdate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="店铺id" align="center" prop="shopId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="success" icon="Promotion" @click="openMassSend(scope.row)" v-hasPermi="['order:coupons:send']">群发</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:coupons:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:coupons:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="群发优惠券" v-model="sendOpen" width="520px" append-to-body>
      <el-form ref="sendRef" :model="sendForm" :rules="sendRules" label-width="100px">
        <el-form-item label="优惠券ID">
          <el-input v-model="sendForm.couponsId" disabled />
        </el-form-item>

        <el-form-item label="发放对象" prop="targetType">
          <el-radio-group v-model="sendForm.targetType">
            <el-radio label="ALL">全部用户</el-radio>
            <el-radio label="LEVEL">按会员等级</el-radio>
            <el-radio label="USERS">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="sendForm.targetType==='LEVEL'" label="会员等级" prop="level">
          <el-select v-model="sendForm.level" placeholder="请选择会员等级" style="width: 240px">
            <el-option label="普通会员" :value="1" />
            <el-option label="黄金会员" :value="2" />
            <el-option label="白金会员" :value="3" />
            <el-option label="钻石会员" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="sendForm.targetType==='USERS'" label="用户标识" prop="targets">
          <el-input
              v-model="sendForm.targets"
              type="textarea"
              :rows="4"
              placeholder="请输入用户ID或手机号，多个用英文逗号分隔"
          />
        </el-form-item>

        <el-form-item label="每人限领" prop="perUserLimit">
          <el-input-number v-model="sendForm.perUserLimit" :min="1" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sendOpen=false">取 消</el-button>
          <el-button type="primary" @click="submitSend">发 放</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="couponsRef" :model="form" :rules="rules" >
        <el-form-item label="优惠券描述" prop="couponsDesc">
          <el-input v-model="form.couponsDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponsType">
          <el-input v-model="form.couponsType" placeholder="1: '满减券',2: '折扣券', 3: '代金券', 4: '赠品券'" />
        </el-form-item>
        <el-form-item label="折扣额度" prop="discountAmount">
          <el-input v-model="form.discountAmount" placeholder="请输入折扣额度" />
        </el-form-item>
        <el-form-item label="减价额度" prop="reductionAmount">
          <el-input v-model="form.reductionAmount" placeholder="请输入减价额度" />
        </el-form-item>
        <el-form-item label="优惠券使用条件" prop="couponsCondition">
          <el-input v-model="form.couponsCondition" placeholder="请输入优惠券使用条件" />
        </el-form-item>
        <el-form-item label="限制使用日期" prop="couponsLimitdate">
          <el-date-picker clearable
            v-model="form.couponsLimitdate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择限制使用日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺id" prop="shopId">
          <el-input v-model="form.shopId" placeholder="请输入店铺id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupons">
import { listCoupons, getCoupons, delCoupons, addCoupons, updateCoupons, sendCoupons } from "@/api/order/coupons"
const { proxy } = getCurrentInstance()

const couponsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    couponsType: null,
    couponsDesc: null,
    discountAmount: null,
    reductionAmount: null,
    couponsCondition: null,
    couponsStatus: null,
    couponsLimitdate: null,
    shopId: null,
  },
  rules: {
    couponsType: [
      { required: true, message: "优惠类型不能为空", trigger: "change" }
    ],
    couponsDesc: [
      { required: true, message: "优惠券描述不能为空", trigger: "blur" }
    ],
    couponsCondition: [
      { required: true, message: "优惠券使用条件不能为空", trigger: "blur" }
    ],
    couponsStatus: [
      { required: true, message: "优惠券状态不能为空", trigger: "change" }
    ],
    couponsLimitdate: [
      { required: true, message: "限制使用日期不能为空", trigger: "blur" }
    ],
    shopId: [
      { required: true, message: "店铺id不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "修改时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询优惠券列表 */
function getList() {
  loading.value = true
  listCoupons(queryParams.value).then(response => {
    couponsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 格式化优惠类型（假设数据库存储：1-满减券，2-折扣券，3-代金券，4-赠品券）
const formatCouponType = (row, column, cellValue) => {
  const typeMap = {
    1: { text: '满减券', color: '#4CAF50' }, // 绿色
    2: { text: '折扣券', color: '#2196F3' }, // 蓝色
    3: { text: '代金券', color: '#FF9800' }, // 橙色
    4: { text: '赠品券', color: '#F44336' }  // 红色
    // 可根据实际业务扩展其他类型
  };
  // 获取当前类型的配置（默认未知类型）
  const config = typeMap[cellValue] || { text: `未知类型(${cellValue})`, color: '#9E9E9E' };
  // 返回带内联样式的span标签
  return `<span style="color: ${config.color}; font-weight: 500;">${config.text}</span>`;
};

// 格式化优惠券状态（假设数据库存储：1-未领取，2-未使用，3-已使用，4-已过期）
const formatCouponStatus = (row, column, cellValue) => {
  // 定义状态映射：包含文字和对应颜色（根据业务场景调整）
  const statusMap = {
    1: { text: '未领取', color: '#9E9E9E', bgColor: '#F5F5F5' }, // 灰色（未激活）
    2: { text: '未使用', color: '#4CAF50', bgColor: '#E8F5E9' },     // 绿色（正常）
    3: { text: '已使用', color: '#FF9800', bgColor: '#FFF3E0' },   // 橙色（警告）
    4: { text: '已过期', color: '#F44336', bgColor: '#FFEBEE' }    // 红色（错误）
  };

  // 获取当前状态的配置（默认未知状态）
  const config = statusMap[cellValue] || {
    text: `未知状态(${cellValue})`,
    color: '#757575',
    bgColor: '#EEEEEE'
  };

  // 返回带样式的标签（文字颜色+背景色，增强视觉区分）
  return `<span style="
    color: ${config.color};
    background-color: ${config.bgColor};
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  ">${config.text}</span>`;
};

//发送优惠券
const sendOpen = ref(false)
const sendForm = reactive({
  couponsId: null,
  targetType: 'ALL',      // ALL | LEVEL | USERS
  level: null,            // 当 targetType=LEVEL 时必填
  targets: '',            // 当 targetType=USERS 时必填（逗号分隔）
  perUserLimit: 1
})
const sendRules = {
  targetType: [{ required: true, message: '请选择发放对象', trigger: 'change' }],
  level: [{
    validator: (r,v,cb)=> {
      if (sendForm.targetType==='LEVEL' && (v===null || v===undefined)) return cb(new Error('请选择会员等级'))
      cb()
    }, trigger: 'change'
  }],
  targets: [{
    validator: (r,v,cb)=> {
      if (sendForm.targetType==='USERS' && (!v || !String(v).trim())) return cb(new Error('请输入用户标识'))
      cb()
    }, trigger: 'blur'
  }],
  perUserLimit: [{ required: true, message: '请填写每人限领数量', trigger: 'change' }]
}

function openMassSend(row) {
  sendForm.couponsId = row.couponsId
  sendForm.targetType = 'ALL'
  sendForm.level = null
  sendForm.targets = ''
  sendForm.perUserLimit = 1
  sendOpen.value = true
}

function submitSend() {
  proxy.$refs.sendRef.validate(valid => {
    if (!valid) return
    const payload = {
      couponsId: sendForm.couponsId,
      targetType: sendForm.targetType,
      level: sendForm.targetType==='LEVEL' ? sendForm.level : null,
      targets: sendForm.targetType==='USERS'
          ? String(sendForm.targets).split(',').map(s=>s.trim()).filter(Boolean)
          : null,
      perUserLimit: sendForm.perUserLimit
    }
    sendCoupons(payload).then(() => {
      proxy.$modal.msgSuccess('优惠券已发放')
      sendOpen.value = false
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    couponsId: null,
    couponsType: null,
    couponsDesc: null,
    discountAmount: null,
    reductionAmount: null,
    couponsCondition: null,
    couponsStatus: null,
    couponsLimitdate: null,
    shopId: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("couponsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.couponsId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加优惠券"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _couponsId = row.couponsId || ids.value
  getCoupons(_couponsId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改优惠券"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponsRef"].validate(valid => {
    if (valid) {
      if (form.value.couponsId != null) {
        updateCoupons(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCoupons(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _couponsIds = row.couponsId || ids.value
  proxy.$modal.confirm('是否确认删除优惠券编号为"' + _couponsIds + '"的数据项？').then(function() {
    return delCoupons(_couponsIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/coupons/export', {
    ...queryParams.value
  }, `coupons_${new Date().getTime()}.xlsx`)
}

getList()
</script>
